package com.mulanweb.api.module.controller;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.RandomStringGenerator;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.db.common.WxParaFormatter;
import com.mulanweb.handler.CouponHandler;
import com.mulanweb.handler.wechat.SentModelMessageHandler;
import com.mulanweb.handler.wechat.UserHandler;
import com.mulanweb.utils.AseUtils;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.utils.RandomUtil;
import com.mulanweb.utils.WxSignUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/8/26.
 */
@ValidateFile
public class OrderController extends BaseController {

    public void searchUserOrder() {
        String openId = getSessionAttr("openId"); //"oULNBwOvt_D2A_8se1bQOQ06ky0w";//
        if (UserHandler.userNotNull(openId)) {
            //if (true) {
            User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id=?", openId);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
          /*  SQLGenerateHelper helper1 = new SQLGenerateHelper("`visa_order`", "create_time desc");
            helper1.addEqualsCondition("user_id", user.getId());
            Page<VisaOrder> VisaOrderPage = VisaOrder.dao.paginate(getParaToInt("PageNumber"), getParaToInt("PageSize"), helper1.getSqlSelect(), helper1.getSqlExceptSelect(), helper1.getQueryParas());

            for (VisaOrder vo : VisaOrderPage.getList()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("order", vo);
                Map<String,Object> target = new HashMap<String,Object>();
                VisaChild visaChild = VisaChild.dao.findById(vo.getVisaChildId());
                Visa visa = Visa.dao.findById(visaChild.getParentId());
                target.put("title",visa.getTitle());
                target.put("price",visaChild.getPrice());
                target.put("oldPrice",visaChild.getPriceOld());
                Photo photo = Photo.dao.findFirst("SELECT * FROM photo WHERE type_id = 18 AND target_id = ?",visa.getId());
                if(photo != null){
                    target.put("contentLogo",photo.getPath());
                }
                map.put("visaTag",true);
                map.put("target",target);
                list.add(map);
            }*/

            SQLGenerateHelper helper = new SQLGenerateHelper("`order`", "create_time desc");
            helper.addEqualsCondition("user_id", user.getId());
            helper.addIsNullCondition("delete_time");
            Page<Order> page = Order.dao.paginate(getParaToInt("PageNumber"), getParaToInt("PageSize"), helper.getSqlSelect(), helper.getSqlExceptSelect(), helper.getQueryParas());
            for (Order oo : page.getList()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("order", oo);
                if (oo.getTypeId() == 23) {
                    map.put("target", Ticket.dao.findById(oo.getTargetId()));
                } else if (oo.getTypeId() == 24) {
                    map.put("target", Chartered.dao.findById(oo.getTargetId()));
                }
                list.add(map);
            }
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("DataList", list);
            result.put("PageNumber", page.getPageNumber());
            result.put("PageSize", page.getPageSize());
            result.put("TotalPage", page.getTotalPage());
            result.put("TotalRow", page.getTotalRow());
            result.put("ReturnCode", 1);
            renderJson(result);
        }
    }

    @ValidateForm
    public void checkPayStatus() throws Exception {
        String orderNumber = getPara("orderNumber");
        String appid = Constant.WeChatFinalValue.APPID;//微信分配的公众账号ID（企业号corpid即为此appId）
        String mch_id = Constant.WeChatFinalValue.MCHID;//微信支付分配的商户号
        String nonce_str = RandomStringGenerator.getRandomStringByLength(32);//这是随机字符串
        String sign = null;
        SortedMap<Object, Object> para = new TreeMap<Object, Object>();
        para.put("appid", appid);
        para.put("mch_id", mch_id);
        para.put("nonce_str", nonce_str);
        para.put("out_trade_no", orderNumber);
        sign = WxSignUtil.createGetPrepayIdSign(para);//进行微信特定签名
        para.put("sign", sign);
        String xml = WxParaFormatter.getRequestXml(para);//将所有参数转换成xml格式

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(Constant.WeChatFinalValue.QUERY_ORDER_URL);
        post.addHeader("Content/Type", "application/xml");
        StringEntity stringEntity = new StringEntity(xml, ContentType.create("application/xml", "UTF-8"));
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = null;
        try {
            resp = client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int returnCode = resp.getStatusLine().getStatusCode();
        String str = "";
        if (200 <= returnCode && 300 >= returnCode) {
            try {
                str = (EntityUtils.toString(resp.getEntity()));

                Map<String, String> result = WxParaFormatter.xmlToMap(str);
                Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number = ?", orderNumber);
                if (result.containsKey("trade_state") && "SUCCESS".equals(result.get("trade_state"))) {
                    String verifyCode1 = RandomUtil.createRandomNumber(8);
                    String verifyCode = AseUtils.aesEncrypt(verifyCode1, Constant.XinXiLan.ORDER_AES_KEY);
                    while (StrKit.notNull(Order.dao.findFirst("SELECT * FROM `order` WHERE verify_code = ?", verifyCode))) {
                        verifyCode1 = RandomUtil.createRandomNumber(8);
                        verifyCode = AseUtils.aesEncrypt(verifyCode1, Constant.XinXiLan.ORDER_AES_KEY);
                    }
                    order.setVerifyCode(verifyCode);
                    order.setVerifyCodeStatus(13L);//13，待认证状态
                    order.setPaymentTime(new Date());
                    order.setStatusId(4L);//4,订单已支付状态
                    if (order.update()) {
                        String title = "";
                        Seller seller = Seller.dao.findById(order.getSellerId());
                        if (order.getTypeId() == 23) {
                            Ticket ticket = Ticket.dao.findById(order.getTargetId());
                            title = ticket.getTitle();
                            SentModelMessageHandler.sentSuccessPayModel(order.getOrderNumber(), title, AseUtils.aesDecrypt(order.getVerifyCode(), Constant.XinXiLan.ORDER_AES_KEY), seller.getMobileNumber(), seller.getEmail(), order.getPaymentTime(), getSessionAttr("openId"), seller.getYuyue());
                        } else if (order.getTypeId() == 24) {
                            Chartered chartered = Chartered.dao.findById(order.getTargetId());
                            title = chartered.getTitle();
                            CarBrand carBrand = CarBrand.dao.findById(chartered.getCarBrandId());
                            SentModelMessageHandler.sentSuccessPayModel(order.getOrderNumber(), title, AseUtils.aesDecrypt(order.getVerifyCode(), Constant.XinXiLan.ORDER_AES_KEY),
                                    seller.getMobileNumber(), seller.getEmail(), order.getPaymentTime(), getSessionAttr("openId"),
                                    carBrand.getName(), chartered.getPlateNumber(), seller.getYuyue());
                        }


                        returnJson(1, "操作成功");
                    } else {
                        returnJson(0, "更新失败，系统错误");
                    }
                } else {
                    //订单未支付已过期，优惠券恢复使用次数
                    CouponHandler.cancelCoupon(order.getId());
                    returnJson(0, "更新失败，未完成支付");
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
        }
    }

    @ValidateForm
    public void getDetail() {
        Long orderId = getParaToLong("orderId");
        Order order = Order.dao.findById(orderId);
        renderJson(order);
    }

    @ValidateForm
    public void getUserVerifyCode() throws Exception {
        String openId = getSessionAttr("openId");//"oULNBwOvt_D2A_8se1bQOQ06ky0w";//
        Map<String, Object> map = new HashMap<String, Object>();
        if (UserHandler.userNotNull(openId)) {
            User user = User.dao.findFirst("SELECT * FROM `user` WHERE open_id =?", openId);
            Long targetId = getParaToLong("targetId");
            Integer typeId = getParaToInt("typeId");
            String orderNumber = getPara("orderNumber");
            Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE user_id=? AND target_id = ? AND type_id = ? AND order_number = ?", user.getId(), targetId, typeId, orderNumber);
            if (StrKit.notNull(order)) {
                map.put("ReturnCode", 1);
                map.put("ReturnStr", order.getVerifyCode() != null ? AseUtils.aesDecrypt(order.getVerifyCode(), Constant.XinXiLan.ORDER_AES_KEY) : "兑换码为空");
            } else {
                map.put("ReturnCode", 0);
                map.put("ReturnStr", "订单不存在或已删除");
            }
        } else {
            map.put("ReturnCode", 0);
            map.put("ReturnStr", Constant.PromptMessage.NOT_EXIST_USER);
        }
        renderJson(map);
    }

    @ValidateForm
    public synchronized void cancelOrder() {

        String openId = getSessionAttr("openId"); // "oULNBwOvt_D2A_8se1bQOQ06ky0w";//

        List<Order> list = Order.dao.find("SELECT *  FROM `order` WHERE DATE_FORMAT(create_time,'%Y-%m-%d') = ? AND user_id=?", DateUtil.dataToYyyyMmDd(new Date()), User.dao.findFirst("SELECT * FROM `user` WHERE open_id=?", openId).getId());
        if (list.size() > 5) {
            returnJson(0, "每日只能取消5次订单,剩余次数为0");
            return;
        }
        if (openId != null && UserHandler.userNotNull(openId)) {
            String orderNumber = getPara("orderNumber");
            Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number=?", orderNumber);
            if (order != null) {
                order.setStatusId(6L);//6 = 订单已过期
                order.update();
                if (order.getTypeId() == 23) {
                    Ticket ticket = Ticket.dao.findById(order.getTargetId());
                    if (ticket != null) {
                        ticket.setSurplusTotal(ticket.getSurplusTotal() + order.getAmount());
                        ticket.update();
                    }
                    //回复优惠券使用次数
                    CouponHandler.cancelCoupon(order.getId());
                }
                returnJson(1, "每日只能取消5次订单,剩余次数为" + (5 - list.size()));
            } else {
                returnFailureJson();
            }
        }
    }
}